# -*- coding: utf-8 -*-
from PyQt5.QtWidgets import QApplication, QWidget, QMessageBox, QTableWidgetItem
from Ui.book import Ui_Form
import sys
from SQL.db import Session, User, BookManager, BookType
from sqlalchemy import and_


class MainWindow(QWidget):
    isLogin = True

    def __init__(self):
        super().__init__()
        self.initUi()

    def initUi(self):
        self.ui = Ui_Form()
        self.ui.setupUi(self)

        self.ui.login_button.clicked.connect(self.login)
        self.ui.reset_button.clicked.connect(self.reset)

        self.ui.bookManager_button.clicked.connect(lambda: self.toggle_stacked_view(1))
        self.ui.bookInfoManager_button.clicked.connect(lambda: self.toggle_stacked_view(2))
        self.ui.bookTypeManager_button.clicked.connect(lambda: self.toggle_stacked_view(3))
        self.ui.sysConfig_button.clicked.connect(lambda: self.toggle_stacked_view(4))

        self.ui.logout_btn.clicked.connect(self.logout)
        self.ui.sumbit_btn.clicked.connect(self.modify_password)

        self.ui.add_book_btn.clicked.connect(self.add_book_info)
        self.ui.reset_book_btn.clicked.connect(self.reset_book_info_)

        self.ui.book_type_btn.clicked.connect(self.add_book_type)

        self.ui.search_btn.clicked.connect(self.search_book_info)

        self.flush_bookType_comboBox()
        self.flush_bookInfo_table()

        self.ui.tableWidget.clicked.connect(self.table_clicked_event)

        self.ui.modify_btn.clicked.connect(self.modify_book_info)
        self.ui.del_btn.clicked.connect(self.delete_table_row)

    def login(self):
        """ 用户登录 """
        username = self.ui.username_edit.text().strip()
        password = self.ui.password_edit.text().strip()

        if not all([username, password]):
            QMessageBox.warning(self, "错误提示", "用户名或密码为空")
            return
        elif self.isLogin:
            QMessageBox.information(self, "提示", "您已登录!")
            return

        # 获取用户名和密码
        session = Session()
        user = session.query(User).filter_by(name=username, password=password).first()
        if user:
            QMessageBox.information(self, '登录成功', "登录成功，欢迎您使用图书管理系统!")
            self.ui.status_label.setText("状态：已登录")
            self.ui.password_edit.clear()
            self.isLogin = True
            self.ui.user_name_label.setText(user.name)
            session.close()
        else:
            QMessageBox.warning(self, "错误提示", "用户名或密码错误!")
            self.ui.password_edit.clear()

    def reset(self):
        """ 重置登录信息 """
        self.ui.username_edit.clear()
        self.ui.password_edit.clear()

    def toggle_stacked_view(self, page: int):
        """ 切换堆叠视图 """
        if self.isLogin:
            self.ui.stackedWidget.setCurrentIndex(page)
        else:
            QMessageBox.warning(self, "错误提示", "您当前还未登录")

    def logout(self):
        """ 退出登录 """
        self.ui.stackedWidget.setCurrentIndex(0)
        self.isLogin = False
        self.ui.status_label.setText("状态：未登录")

    def modify_password(self):
        """ 修改密码 """
        old_password = self.ui.old_passwod.text().strip()
        new_password = self.ui.new_password.text().strip()
        confirm_password = self.ui.confirm_passwrod.text().strip()

        if not all([old_password, new_password, confirm_password]):
            QMessageBox.warning(self, "错误提示", "密码填写不完整!")
            return
        elif new_password != confirm_password:
            QMessageBox.warning(self, "错误提示", "两次密码不一致")
            return

        session = Session()
        user = session.query(User).filter_by(name=self.ui.user_name_label.text().strip(), password=old_password).first()

        if user:
            user.password = confirm_password
            session.commit()
            QMessageBox.information(self, "提示", "密码修改成功")
            session.close()
        else:
            QMessageBox.warning(self, "错误提示", "原密码不正确")

        self.ui.old_passwod.clear()
        self.ui.new_password.clear()
        self.ui.confirm_passwrod.clear()

    def add_book_info(self):
        """ 添加图书 """
        b_name = self.ui.add_book_name.text().strip()
        b_author = self.ui.add_book_author.text().strip()
        b_price = self.ui.add_book_price.text().strip()
        b_type = self.ui.add_book_type_comboBox.currentText()
        b_desc = self.ui.add_book_desc.toPlainText().strip()
        b_sex = self.ui.add_male_radioButton.text()

        if self.ui.add_female_radioButton.isChecked():
            b_sex = self.ui.add_female_radioButton.text()

        if not all([b_name, b_author, b_price]):
            QMessageBox.warning(self, "错误提示", "书籍信息填写不完整")
            return

        session = Session()
        try:
            book = BookManager(
                b_name=b_name,
                b_author=b_author,
                b_price=b_price,
                b_type=b_type,
                b_desc=b_desc,
                b_sex=b_sex
            )
            session.add(book)
            session.commit()
            QMessageBox.information(self, "提示", "书籍添加成功")
        except Exception as e:
            session.rollback()
            QMessageBox.warning(self, "错误提示", str(e))
        finally:
            session.close()
            self.reset_book_info_()
            self.flush_bookInfo_table()

    def reset_book_info_(self):
        """ 重置书籍信息 """
        self.ui.add_book_name.clear()
        self.ui.add_book_price.clear()
        self.ui.add_book_author.clear()
        self.ui.add_book_desc.clear()

    def add_book_type(self):
        """ 添加图书类别 """
        t_name = self.ui.book_type_edit.text().strip()
        t_desc = self.ui.book_type_desc.toPlainText().strip()

        if not t_name:
            QMessageBox.warning(self, "错误提示", "图书类别名称不能为空")
            return

        session = Session()
        try:
            book_type_name = BookType(
                b_type=t_name,
                b_desc=t_desc
            )
            session.add(book_type_name)
            session.commit()
            QMessageBox.information(self, "提示", "图书类别添加成功")
        except Exception as e:
            session.rollback()
            QMessageBox.warning(self, "错误提示", str(e))
        finally:
            session.close()
            self.reset_book_type_()
            self.flush_bookType_comboBox()

    def reset_book_type_(self):
        """ 重置图书类别信息 """
        self.ui.book_type_edit.clear()
        self.ui.book_type_desc.clear()

    def flush_bookType_comboBox(self):
        """ 刷新图书类别下拉框 """
        self.ui.search_book_type_comboBox.clear()
        self.ui.edit_book_type_comboBox.clear()
        self.ui.add_book_type_comboBox.clear()

        session = Session()
        book_types = session.query(BookType).all()

        self.ui.search_book_type_comboBox.addItem("全部")
        for b in book_types:
            self.ui.search_book_type_comboBox.addItem(b.b_type)
            self.ui.edit_book_type_comboBox.addItem(b.b_type)
            self.ui.add_book_type_comboBox.addItem(b.b_type)

        session.close()

    def flush_bookInfo_table(self):
        """ 刷新书籍表格 """
        self.clear_table_row()

        session = Session()
        book_infos = session.query(BookManager).all()

        self.ui.tableWidget.setRowCount(len(book_infos))
        self.ui.tableWidget.setColumnCount(7)
        for row, b in enumerate(book_infos):
            self.ui.tableWidget.setItem(row, 0, QTableWidgetItem(str(b.id)))
            self.ui.tableWidget.setItem(row, 1, QTableWidgetItem(str(b.b_name)))
            self.ui.tableWidget.setItem(row, 2, QTableWidgetItem(str(b.b_price)))
            self.ui.tableWidget.setItem(row, 3, QTableWidgetItem(str(b.b_author)))
            self.ui.tableWidget.setItem(row, 4, QTableWidgetItem(str(b.b_sex)))
            self.ui.tableWidget.setItem(row, 5, QTableWidgetItem(str(b.b_type)))
            self.ui.tableWidget.setItem(row, 6, QTableWidgetItem(str(b.b_desc)))

        self.ui.tableWidget.update()
        session.close()

    def search_book_info(self):
        """ 搜搜书籍信息 """
        book_name = self.ui.search_book_name.text().strip()
        book_author = self.ui.search_book_author.text().strip()
        book_type = self.ui.search_book_type_comboBox.currentText()

        session = Session()

        # 动态构建查询语句
        # 定义查询条件
        conditions = []

        if book_name != "":
            conditions.append(BookManager.b_name == book_name)

        if book_author != "":
            conditions.append(BookManager.b_author == book_author)

        if book_type != "全部":
            conditions.append(BookManager.b_type == book_type)

        # 构建查询语句
        books = session.query(BookManager).filter(and_(*conditions)).all() if len(conditions) > 0 else session.query(
            BookManager).all()

        if len(books) == 0:
            QMessageBox.information(self, "提示", "搜索结果为空!")
            return

        self.clear_table_row()

        self.ui.tableWidget.setRowCount(len(books))
        self.ui.tableWidget.setColumnCount(7)

        for row, b in enumerate(books):
            self.ui.tableWidget.setItem(row, 0, QTableWidgetItem(str(b.id)))
            self.ui.tableWidget.setItem(row, 1, QTableWidgetItem(str(b.b_name)))
            self.ui.tableWidget.setItem(row, 2, QTableWidgetItem(str(b.b_price)))
            self.ui.tableWidget.setItem(row, 3, QTableWidgetItem(str(b.b_author)))
            self.ui.tableWidget.setItem(row, 4, QTableWidgetItem(str(b.b_sex)))
            self.ui.tableWidget.setItem(row, 5, QTableWidgetItem(str(b.b_type)))
            self.ui.tableWidget.setItem(row, 6, QTableWidgetItem(str(b.b_desc)))

        self.ui.tableWidget.update()
        session.close()

    def clear_table_row(self):
        """ 清除表格所有行 """
        row_count = self.ui.tableWidget.rowCount()

        if row_count > 0:
            for _ in range(row_count):
                self.ui.tableWidget.removeRow(0)

    def table_clicked_event(self, index):
        """ 表格的点击事件
            index: QModelIndex
        """

        # 获取行索引
        row_index = index.row()

        # 设置图书编号、书名、价格、作者、描述信息
        self.ui.edit_book_series.setText(self.ui.tableWidget.item(row_index, 0).text())
        self.ui.edit_book_name.setText(self.ui.tableWidget.item(row_index, 1).text())
        self.ui.edit_book_price.setText(self.ui.tableWidget.item(row_index, 2).text())
        self.ui.edit_book_author.setText(self.ui.tableWidget.item(row_index, 3).text())
        self.ui.edit_book_desc.setPlainText(self.ui.tableWidget.item(row_index, 6).text())

        # 性别设置
        current_sex = "男" if self.ui.edit_male_radioButton.isChecked() else '女'
        t_sex = self.ui.tableWidget.item(row_index, 4).text()

        if current_sex != t_sex and self.ui.edit_male_radioButton.isChecked():
            self.ui.edit_female_radioButton.setChecked(True)
        else:
            self.ui.edit_male_radioButton.setChecked(True)

    def modify_book_info(self):
        """ 修改图书信息 """
        b_series = self.ui.edit_book_series.text()
        b_name = self.ui.edit_book_name.text()
        b_price = self.ui.edit_book_price.text()
        b_author = self.ui.edit_book_author.text()
        b_type = self.ui.edit_book_type_comboBox.currentText()
        b_sex = "男" if self.ui.edit_male_radioButton.isChecked() else "女"
        b_desc = self.ui.edit_book_desc.toPlainText()

        session = Session()
        try:
            book = session.query(BookManager).filter_by(id=b_series, b_name=b_name).first()
            book.id = b_series
            book.b_name = b_name
            book.b_price = b_price
            book.b_author = b_author
            book.b_type = b_type
            book.b_sex = b_sex
            book.b_desc = b_desc
            session.commit()
            QMessageBox.information(self, "提示", "书籍信息修改成功")
            self.flush_bookInfo_table()
        except Exception as e:
            QMessageBox.warning(self, "错误提示", str(e))
            session.rollback()
        finally:
            session.close()

    def delete_table_row(self):
        """ 删除选中的行 """
        # currentIndex 返回 ModelIndex对象
        current_index = self.ui.tableWidget.currentIndex()
        row_index = current_index.row()

        if row_index == -1:
            QMessageBox.information(self, "提示", "请选择你要删除的行")
            return

        session = Session()
        try:
            book = session.query(BookManager).filter_by(
                id=self.ui.tableWidget.item(row_index, 0).text(),
                b_name=self.ui.tableWidget.item(row_index, 1).text()
            ).first()
            session.delete(book)
            session.commit()
            self.ui.tableWidget.removeRow(row_index)
            QMessageBox.information(self, "提示", "删除成功")
        except Exception as e:
            session.rollback()
            QMessageBox.warning(self, "错误提示", str(e))
        finally:
            session.close()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())
